package com.example.helloworldtext2.fragments;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.helloworldtext2.R;
import com.example.helloworldtext2.adapter.HomeAdapter;
import com.example.helloworldtext2.api.ArticleApi;
import com.example.helloworldtext2.model.Article;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private RecyclerView recyclerView;
    private ArrayList<Article> articleList;
    private HomeAdapter homeAdapter;
    private int currentPage = 1;
    private boolean isLoading = false;
    private boolean hasMoreData = true;
    private ArticleApi articleApi;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        articleApi = new ArticleApi();
        initView(view);
        loadData();
        return view;
    }
    public void initView(View view){
        recyclerView = view.findViewById(R.id.home);

//        创建瀑布管理器
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        // 设置LayoutManager
        recyclerView.setLayoutManager(layoutManager);
        articleList = new ArrayList<>();
//        引入适配器
        homeAdapter = new HomeAdapter(layoutManager, articleList);
        recyclerView.setAdapter(homeAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setItemViewCacheSize(20);
        
        // 添加滚动监听器实现触底加载
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                
                // 获取最后一个可见项的位置
                int[] lastVisibleItemPositions = layoutManager.findLastVisibleItemPositions(null);
                int lastVisibleItemPosition = getLastVisibleItem(lastVisibleItemPositions);
                
                // 判断是否需要加载更多数据
                if (!isLoading && hasMoreData && 
                    (lastVisibleItemPosition >= articleList.size() - 3)) {
                    loadNextPage();
                }
            }
            
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                // 解决底部留白问题
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    layoutManager.invalidateSpanAssignments();
                }
            }
        });
    }
    
    // 获取最后一个可见项的位置
    private int getLastVisibleItem(int[] lastVisibleItemPositions) {
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) {
            if (i == 0) {
                maxSize = lastVisibleItemPositions[i];
            } else if (lastVisibleItemPositions[i] > maxSize) {
                maxSize = lastVisibleItemPositions[i];
            }
        }
        return maxSize;
    }
    
    private void loadData() {
        // 添加示例数据
//        for (int i = 0; i < 20; i++) {
//            Article item = new Article(
//                    i,
//                    "标题 " + (i + 1),
//                    "这是一个视频描述内容，用于展示瀑布流布局效果。",
//                    "",
//                    "https://picsum.photos/200/300?random=" + i,
//                    "作者" + (i + 1),
//                    "",
//                    new ArrayList<>(),
//                    "00:00"
//            );
//            articleList.add(item);
//        }
//        homeAdapter.notifyDataSetChanged();
        // 清空现有数据
        if(articleList.size()>0){
            articleList.clear();
        }

        currentPage = 1;
        hasMoreData = true;

        // 发起网络请求获取视频数据
        fetchVideoDataFromAPI(currentPage);
    }
    //    获取视频数据
    private void fetchVideoDataFromAPI(int page) {
        if (isLoading || !hasMoreData) {
            return;
        }

        isLoading = true;

        articleApi.getVideoList(page, 10, new ArticleApi.VideoListListener() {
            @Override
            public void onSuccess(JSONArray videoArray, int page, boolean hasMore) {
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        try {
                            List<Article> articles = articleApi.parseVideoData(videoArray);
                            updateVideoData(articles, page);
                            // 更新分页信息
                            currentPage = page;
                            hasMoreData = hasMore;
                            isLoading = false;
                        } catch (JSONException e) {
                            isLoading = false;
                            Toast.makeText(getContext(), "解析视频数据失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }

            @Override
            public void onError(String error) {
                isLoading = false;
                if (getActivity() != null) {
                    getActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "获取视频数据失败: " + error, Toast.LENGTH_SHORT).show();
                        // 第一页加载失败时加载示例数据
//                        if (page == 1) {
//                            loadSampleData();
//                        }
                    });
                }
            }
        });
    }

    //更新视频数据
    private void updateVideoData(List<Article> articles, int page) {
        Log.d("HomeFragment", "Updating video data: " + articles.size() + " articles, page: " + page);
        // 如果是第一页，清空现有数据并刷新
        if (page == 1) {
            articleList.clear();
            articleList.addAll(articles);
            Log.d("HomeFragment", "First page data, total items: " + articleList.size());
            homeAdapter.notifyDataSetChanged();
        } else {
            // 使用适配器的添加方法，避免整个列表刷新导致的布局跳动
            Log.d("HomeFragment", "Appending data, total items before: " + articleList.size());
            homeAdapter.addArticles(articles);
            Log.d("HomeFragment", "Appending data, total items after: " + articleList.size());
        }
    }
    
    // 加载下一页数据
    private void loadNextPage() {
        if (!isLoading && hasMoreData) {
            Log.d("HomeFragment", "Loading next page: " + (currentPage + 1));
            fetchVideoDataFromAPI(currentPage + 1);
        }
    }
}